import React from 'react';
import Markdown from 'markdown-to-jsx';
import SyntaxHighlighter from 'react-syntax-highlighter';
import { prism } from 'react-syntax-highlighter/dist/esm/styles/prism';
import hljs from 'highlight.js'
import 'highlight.js/styles/github.css';

import markdownStyles from '@/common/css/markdown.module.less';

interface IOverrideCodeProp {
  className: string;
  children: any;
}

/**
 * [](https://github.com/quantizor/markdown-to-jsx?tab=readme-ov-file#syntax-highlighting)
 * [](https://github.com/highlightjs/highlight.js)
 * 不生效？
 * @deprecated
 */
class SyntaxHighlightedCode extends React.Component<IOverrideCodeProp> {
  codeRef = null;

  constructor(props: IOverrideCodeProp) {
    super(props);
  }

  componentDidUpdate(prevProps: Readonly<IOverrideCodeProp>): void {
    if (prevProps.className !== this.props.className || prevProps.children !== this.props.children) {
      if (!this.codeRef.current) {
        return;
      }
      if (this.props.className?.includes('lang-')) {
        hljs.highlightElement(this.codeRef.current);

        // hljs won't reprocess the element unless this attribute is removed
        this.codeRef.current.removeAttribute('data-highlighted');
      }
    }
  }

  render() {
    return <code {...this.props} ref={ref => this.codeRef = ref} />;
  }
}

interface IProp {
  markdown: string;
}

/**
 * google: markdown-to-jsx class component SyntaxHighlightedCode
 */
class MarkdownRenderer extends React.Component<IProp> {
  constructor(props: IProp) {
    super(props);
  }

  render() {
    const { markdown } = this.props;

    return (
      <div className={markdownStyles['markdown-body']}>
        <Markdown
          options={{
            overrides: {
              // code: SyntaxHighlightedCode,
              code: ({ children, className }) => {
                // const match = /language-(\w+)/.exec(className || '');
                const match = /lang-(\w+)/.exec(className || '');

                return !match ? (
                  <code className={className}>{children}</code>
                ) : (
                  <SyntaxHighlighter language={match[1]} style={prism}>
                    {children}
                  </SyntaxHighlighter>
                );
              },
            },
          }}
        >
          { markdown.replace(/\n/g, '\n\n') }
        </Markdown>
      </div>
    );
  }
}

export default MarkdownRenderer;
